package com.course.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.course.server.common.Constant;
import com.course.server.util.UuidUtils;
import com.wf.captcha.GifCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: Durian
 * @date: 2021/6/5 14:17
 */
@Slf4j
@RestController
public class CaptchaController {

    public static final String BUSINESS_NAME = "验证码";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/captcha")
    public String captcha() {
        GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 4);
        String key = UuidUtils.getUuid();
        String code = gifCaptcha.text().toLowerCase();
        log.info("生成验证码key=[{}], code=[{}]", key, code);
        stringRedisTemplate.opsForValue().set(key, code, Constant.VERIFY_CODE_EXPIRE, TimeUnit.SECONDS);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key", key);
        jsonObject.put("code", code);
        jsonObject.put("image", gifCaptcha.toBase64());
        return jsonObject.toJSONString();
    }
}
